﻿using System;
using System.IO;

namespace Sustainalytics.Reporting.Framework
{
    public class ImageManager
    {
        public static byte[] ImageToByteArray(System.Drawing.Image image)
        {
            var memoryStream = new MemoryStream();
            image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
            return memoryStream.ToArray();
        }

        public static System.Drawing.Image ByteArrayToImage(byte[] buffer)
        {
            var memoryStream = new MemoryStream(buffer);
            var image = System.Drawing.Image.FromStream(memoryStream);
            return image;
        }

        public static byte[] GetPngImage(string filePath)
        {
            filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
            using (var fileStream = File.OpenRead(filePath))
            using (var image = System.Drawing.Image.FromStream(fileStream))
            {
                var memoryStream = new MemoryStream();
                image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
                return memoryStream.ToArray();
            }
        }

        public static byte[] GetJpgImage(string filePath)
        {
            filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
            using (var fileStream = File.OpenRead(filePath))
            using (var image = System.Drawing.Image.FromStream(fileStream))
            {
                var memoryStream = new MemoryStream();
                image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                return memoryStream.ToArray();
            }
        }

        public static void SaveImage(string filePath, byte[] picture)
        {
            using (var fileStream = File.OpenWrite(filePath))
            {
                fileStream.Write(picture, 0, picture.Length);
                fileStream.Close();
            }
        }
    }
}
